package org.example.java.util.concurrency.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock(), 拿不到lock就不罢休，不然线程就一直block。
 * lockInterruptibly会优先响应线程中断，处理响应的方式是抛出InterruptedException。
 * <p/>
 * Created by Juntao.Zhang on 2014/9/11.
 */
public class LockInterruptiblyTest {
  static class MyThread implements Runnable {

    private static Lock lock = new ReentrantLock();

    public void run() {
      try {
        System.out.println(Thread.currentThread().getName() + " running");
//        lock.lock();
        lock.lockInterruptibly();
        TimeUnit.SECONDS.sleep(2);
        lock.unlock();
        System.out.println(Thread.currentThread().getName() + " finished");
      } catch (InterruptedException e) {
        System.out.println(Thread.currentThread().getName() + " interrupted");

      }

    }
  }

  public static void main(String[] args) {
    Thread i1 = new Thread(new MyThread(), "t1");
    Thread i2 = new Thread(new MyThread(), "t2");
    i1.start();
    i2.start();
    i2.interrupt();
  }

}
/**
 如果代码是 lock.lock();
 结果是：
 t1 running
 t2 running
 (这里休眠了2s)
 t2 interrupted
 t1 finished

 如果代码是 lock.lockInterruptibly();
 结果是：
 t1 running
 t2 running
 t2 interrupted
 (这里休眠了2s)
 t1 finished
 */
